

// Config
import { baseUrl } from "../config/environment";

// Hooks
import { getToken } from "./useAuth";
import useToast from "./useToast";
import useLogin from "./useLogin";

// Utils
import qs from "qs";
import { isEmpty } from "lodash";

function useRequest({ url, method = "post", params = {}, data = {} }) {
  const header = {};
  header.authorization = getToken();
  const rawUrl = url;
  url = `${baseUrl}${url}`;

  if (!isEmpty(params)) {
    url = `${url}?${qs.stringify(params)}`;
  }

  return new Promise((resolve, reject) => {
    uni.request({ url, method, header, data })
      .then((res) => {
        if (res.statusCode === 200) {
          switch (res.data.code) {
            case 200:
              resolve(res.data);
              return;

            case 602:
            case 401:
              refreshToken({ url: rawUrl, method, data, params }, resolve);
              return;
          }
        }

        const errMsg = res.data.message || res.data.msg || res.data.error || "请求失败";
        useToast(errMsg);
        reject(res.data);
      })
      .catch((error) => {
        useToast("请求失败");
        reject(error);
      });
  });
}

export default useRequest;

const requestQueue = [];
let isRefreshing = false;
//请求队列，是否正在刷新token
function refreshToken(data, resolve) {
  requestQueue.push(() => {
    resolve(useRequest(data));
  });

  if (!isRefreshing) {
    isRefreshing = true;
    useLogin()
      .then(() => {
        requestQueue.map((cb) => cb());
        requestQueue = [];
      })
      .finally(() => {
        isRefreshing = false;
      });
  }
}
